<template>
  <n-card :bordered="false">
    <n-alert type="warning" class="alert_small m-b-10">
      温馨提示：1.点击子区域可查看子区域列表
      2.点击返回上一级可返回上一级区域列表
    </n-alert>
    <n-alert :show-icon="false" class="m-b-10">
      <n-form :model="search_param" class="search-forms"
              inline
              :show-feedback="false"
              label-placement="left"
              @keydown.enter.prevent="handleSubmitSearch">
        <n-form-item label="区域">
          <n-input v-model:value="search_param.name" placeholder="请输入区域名称查询" style="width:230px"
                   clearable/>
        </n-form-item>
        <n-form-item>
          <SearchButtonGroup @submit="handleSubmitSearch"
                             @reset="()=>(search_param.name=null)"/>
        </n-form-item>
      </n-form>
    </n-alert>
    <data-table ref="region_list"
                :columns="columns"
                :action-column="actionColumn"
                :row-key="(row:Recordable) => row.id"
                :params="search_param"
                list-url="region/list"
                default-serial-number
                serial-number-title="序号">
      <template #toolbarLeft>
        <n-space>
          <n-button type="success" v-permission="['region:add']" @click="()=>(addEditRegion=true)">
            <n-icon :size="18">
              <AddSharp/>
            </n-icon>
            新增
          </n-button>
          <n-button v-if="search_param.pId" @click="goBack">
            <n-icon :size="18">
              <ReturnDownBackSharp/>
            </n-icon>
            返回上一级
          </n-button>
        </n-space>
      </template>
    </data-table>
  </n-card>
  <!-- 新增、修改区域 -->
  <n-modal v-model:show="addEditRegion"
           :title="addEditForm.id?'修改区域':'新增区域'" :mask-closable="false"
           :show-icon="false" preset="dialog" @after-leave="closeAddEditRegion">
    <n-form ref="addEditFormRef" :model="addEditForm" :rules="addEditFormRules" require-mark-placement="left"
            label-width="auto" label-placement="left">
      <n-form-item label="上级区域" path="pId">
        <n-tree-select v-model:value="addEditForm.pId" placeholder="请选择上级区域"
                       :options="regionParentOption" clearable/>
      </n-form-item>
      <n-form-item label="名称" path="name">
        <n-input v-model:value="addEditForm.name" placeholder="请填写区域名称" clearable/>
      </n-form-item>
      <n-form-item label="经度" path="longitude">
        <n-input v-model:value="addEditForm.longitude" placeholder="请填写经度" clearable/>
      </n-form-item>
      <n-form-item label="纬度" path="latitude">
        <n-input v-model:value="addEditForm.latitude" placeholder="请填写纬度" clearable/>
      </n-form-item>
      <n-form-item label="热门城市" path="isHot">
        <n-switch :round="false" v-model:value="addEditForm.isHot" :checked-value="1" :unchecked-value="0">
          <template #checked>
            是
          </template>
          <template #unchecked>
            否
          </template>
        </n-switch>
      </n-form-item>
    </n-form>
    <template #action>
      <n-space>
        <n-button @click="()=>(addEditRegion=false)">取消</n-button>
        <n-button type="primary" :loading="handelSubmitLoading" @click="handelSubmitRegion">确定</n-button>
      </n-space>
    </template>
  </n-modal>
</template>
<script setup lang="ts">
import {h, ref, reactive, onMounted} from 'vue'
import SearchButtonGroup from '@components/SearchButtonGroup';
import {FormInst, NPopconfirm, TreeSelectOption, useMessage} from 'naive-ui';
import DataTable from '@components/DataTable'
import DataTableAction from '@components/DataTable/src/components/DataTableAction';
import {delRequest, getRequest, postPutRequest} from '@/api/data.ts'
import {AddSharp} from "@vicons/material";
import {ReturnDownBackSharp} from '@vicons/ionicons5'
import {findParentByKey} from "@/util";

const message = useMessage()

const search_param = ref({
  name: null,
  pId: null,
})
//数据表
const region_list = ref<any>();
const columns = ref([
  {
    title: '首字母',
    key: 'initial',
    width: 60,
  },
  {
    title: '名称',
    key: 'name',
  }, {
    title: '等级',
    key: 'levelName',
    width: 130,
  },
  {
    title: '上级区域',
    key: 'pname',
    width: 130,
  }, {
    title: '经度',
    key: 'longitude',
    width: 100,
  }, {
    title: '纬度',
    key: 'latitude',
    width: 100,
  },{
    title: '热门城市',
    key: 'isHot',
    width: 100,
    align: 'center',
    render(row: { isHot:  number }) {
      const isHotText = row.isHot == 0 ? '否' : '是';
      return h('span', null, {default: () => (isHotText)})
    }
  }, {
    title: '子区域数量',
    key: 'childrenCount',
    width: 110,
    align: 'center'
  }, {
    title: '创建时间',
    key: 'createTime',
    width: 175,
  }, {
    title: '更新时间',
    key: 'updateTime',
    width: 175,
  },
])
//操作列
const actionColumn = reactive({
  width: 170,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record: Recordable) {
    return h(DataTableAction, {
      actions: [
        {
          label: '子区域',
          onClick: handleChildren.bind(null, record.id),
          type: 'primary',
          permission: !record.childrenCount
        },
        {
          label: '修改',
          onClick: handleEdit.bind(null, record),
          type: 'primary',
          permission: ['region:edit']
        },
        {
          label: '删除',
          type: 'error',
          popConfirm: NPopconfirm,
          onPositiveClick: handleDelete.bind(null, record),
          confirm: {
            text: '确定删除当前区域吗？',
          },
          permission: ['region:del']
        },
      ]
    });
  },
});

//新增、修改区域
const regionParentOption = ref<TreeSelectOption[]>([]);
const addEditRegion = ref<boolean>(false);
const addEditFormRef = ref<FormInst | null>(null);
const handelSubmitLoading = ref<boolean>(false);
const addEditForm = ref({
  id: 0,
  pId: null,
  name: '',
  longitude: '',
  latitude: '',
  isHot: 0,
})
const addEditFormRules = ref({
  name: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请填写区域名称'
  },
  pId: {
    type: 'number',
    required: true,
    trigger: 'change',
    message: '请选择上级区域'
  },
})
//查找子区域
const handleChildren = (id: any) => {
  search_param.value.pId = id;
  search_param.value.name = null;
  handleSubmitSearch();
}
//修改
const handleEdit = (record: Recordable) => {
  addEditForm.value.id = record.id;
  addEditForm.value.pId = record.pid;
  addEditForm.value.name = record.name;
  addEditForm.value.longitude = record.longitude;
  addEditForm.value.latitude = record.latitude;
  addEditForm.value.isHot = record.isHot;
  addEditRegion.value = true;
}
//删除
const handleDelete = (record: Recordable) => {
  delRequest('region/del', record.id).then((result: ResponseResult) => {
    if (result.status === 0 && result.code === 200) {
      message.success(result.message, {
        duration: 1500,
        onLeave() {
          region_list.value.reload();
        }
      })
    } else {
      message.error(result.message);
    }
  })
}
//查询
const handleSubmitSearch = () => {
  region_list.value.searchListData();
}
const closeAddEditRegion = () => {
  addEditForm.value.id = 0;
  addEditForm.value.pId = null;
  addEditForm.value.name = '';
  addEditForm.value.longitude = '';
  addEditForm.value.latitude = '';
  addEditForm.value.isHot = 0;
  handelSubmitLoading.value = false;
}
//提交新增、修改区域数据
const handelSubmitRegion = (e: MouseEvent) => {
  e.preventDefault();
  addEditFormRef.value?.validate((errors) => {
    if (!errors) {
      handelSubmitLoading.value = true;
      const url = addEditForm.value.id ? 'region/edit' : 'region/add';
      postPutRequest(url, addEditForm.value, addEditForm.value.id ? 'PUT' : 'POST').then((result: ResponseResult) => {
        if (result.code === 200) {
          message.success(result.message, {
            duration: 1500,
            onLeave() {
              addEditRegion.value = false;
              getRegionParent();
              if (addEditForm.value.id) {
                region_list.value.reload();
              } else {
                region_list.value.searchListData();
              }
            }
          })
        } else {
          message.error(result.message);
          handelSubmitLoading.value = false;
        }
      })
    }
  })
}
//返回上一级
const goBack = () => {
  const region = findParentByKey(regionParentOption.value, search_param.value.pId)
  handleChildren(region ? region.key : null)
}
//为下拉框
const getRegionParent = async () => {
  await getRequest("region/get_tree").then((result: ResponseResult) => {
    const {data} = result;
    const top_region: TreeSelectOption = {label: '省级区域', key: 0};
    data.unshift(top_region);
    regionParentOption.value = data;
  })
}
onMounted(() => {
  getRegionParent();
})

</script>
<style scoped lang="scss">

</style>